
/************************* MODALS [START] ************************************/
function confirmDialog() {
    return {
        autoOpen : false,
        bgiframe : true,
        resizable : false,
        hide : 'blind',
        show : 'blind',
        position: ['center', 'center'],
        height : 150,
        modal : true,
        overlay : {
            backgroundColor : '#000',
            opacity : 0.5
        },
        buttons : {
            OK : function() {
                this.cancelCallback = null;
                $(this).dialog('close');
                if (this.okCallback) this.okCallback(true);
            },
        Cancel : function() {
                $(this).dialog('close');
            }
        },
        close : function(event, ui) {
            if (this.cancelCallback) this.cancelCallback(false);
        }
    };
}

function infoDialog() {
    return {
        autoOpen : false,
        bgiframe : true,
        resizable : false,
        position: ['center', 'center'],
        hide : 'blind',
        show : 'blind',
        height : 150,
        modal : true,
        overlay : {
            backgroundColor : '#000',
            opacity : 0.5
        },
        buttons : {
            OK : function() {
                $(this).dialog('close');
                if (this.okCallback) this.okCallback();
            }
        },
        close : function(event, ui) {
        ;
        }
    };
}

function infoPropsDialog() {
    return {
        autoOpen : false,
        bgiframe : true,
        resizable : true,
        hide : 'blind',
        show : 'blind',
        height : 400,
        width : 500,
        modal : true,
        overlay : {
            backgroundColor : '#000',
            opacity : 0.5
        },
        buttons : {
            OK : function() {
                $(this).dialog('close');
                if (this.okCallback) this.okCallback();
            }
        },
        close : function(event, ui) {
        ;
        }
    };
}


function lockDialog() {
    $('#lockScreen').dialog({
        bgiframe : true,
        modal : true,
        draggable : false,
        resizable : false,
        title : '<div style="color: red; text-align: center;"><h1>Please wait</h1></div>',
        overlay : {
            backgroundColor : '#000',
            opacity : 0.5
        },
        close : function(event, ui) {
            return false;
        }
    });
}

function showPopup(config, id, okCallback, cancelCallback, params) {
    var jqid = id + '-dialog';
    var divobj = document.getElementById(jqid);
    if (!divobj) {
        divobj = document.getElementById(id);
        divobj.id = jqid;
        $('#' + jqid).dialog(config);
    }
    divobj.okCallback = okCallback;
    divobj.cancelCallback = cancelCallback;
    if (params) {
        var inner = divobj.innerHTML;
        if (divobj.originalmessage) {
            inner = divobj.originalmessage;
        } else {
            divobj.originalmessage = inner;
        }
        divobj.innerHTML = inner.replace("#", params);
    }
    $('#' + jqid).dialog('open');
    return divobj;
}

function showConfirm(id, callback, params) {
    showPopup(confirmDialog(), id, callback, null, params);
}
function showConfirm2(id, callback, callback2, params) {
    showPopup(confirmDialog(), id, callback, callback2, params);
}
function showInfo(id, callback, params) {
    showPopup(infoDialog(), id, callback, null, params);
}

function submitForm(form, button) {
    lockScreenForProcess();
    if (button && form.formAction && button.getAttribute('name')) {
        form.formAction.value = button.getAttribute('name');
    }
    $(form).submit();
}

function submitFormAjax(divid, form, url) {
    lockScreenForProcess();
    ajaxLoadTo(divid, url, $(form).serializeArray());
}

function ajaxLoadToWithCb(objid, url, params, onSuccess) {
    $("#" + objid).load(url, params,
        function (responseText, textStatus, XMLHttpRequest) {
            grayScreen(false);
            if (XMLHttpRequest.status != 200) {
                displayErrorMessage(objid, XMLHttpRequest);
            } else {
                if ($.isFunction(onSuccess)) {
                    onSuccess();
                }
            }
        }
        );
}

function ajaxLoadTo(objid, url, params) {
    ajaxLoadToWithCb(objid, url, params, null);
}

function displayErrorMessage(objid, XMLHttpRequest) {
    if (XMLHttpRequest.status==0) {
        $("#" + objid).html('ERROR - Server not reachable');
    } else {
        $("#" + objid).html('ERROR HTTP ' + XMLHttpRequest.status);
    }
}

/************************* MODALS [END] **************************************/
/*****************************************************************************/
/************************* VALIDATOR [START] *********************************/
function textareamax(obj, maxlen) {
    if (obj.value.length>maxlen) obj.value = obj.value.substring(0, maxlen);
}

function validate(obj) {
    var v = obj.value;
    var vr = obj.validation_rules;
    if (!vr) return true;
    if (vr.uppercase) v = v.toUpperCase();
    if (vr.trim) v = jQuery.trim(v);
    if (vr.required && (vr.force || !obj.readOnly) && v.length==0) {
        return validation(obj, false, vr.message);
    }
    if (vr.regex!=null && v.length>0) {
        return validation(obj, vr.regex.test(v), vr.message);
    } else {
        return validation(obj, true, null);
    }
}

function validation(obj, cond, errmsg) {
    var s = obj.id.toString() + '_error';
    var o = document.getElementById(s);
    if (!cond) {
        $(obj).addClass('invalid');
        if (o != null) {
            o.className = 'errorMsg';
            o.innerHTML = errmsg;
        }
    } else {
        $(obj).removeClass('invalid');
        if (o != null) {
            o.className = 'noErrorMsg';
            o.innerHTML = '';
        }
    }
    return cond;
}

function applyReadOnlyStyle(element, condition) {
    if (condition) {
        $(element).addClass("readOnlyStyle");
    } else {
        $(element).removeClass("readOnlyStyle");
    }
}

function cleanFormErrorMsg(theForm) {
    for (var i = 0; i < theForm.length; i++) {
        if (theForm.elements[i].className=='invalid') {
            theForm.elements[i].className = '';
        }
        var element = document.getElementById(theForm.elements[i].id + '_error');
        if (element != null) {
            element.className = 'noErrorMsg';
        }
    }
}

function validateForm(theForm) {
    var result = true;
    for (var i = 0; i < theForm.length; i++) {
        var element = theForm.elements[i];
        if (!validate(element)) {
            result = false;
        }
    }
    return result;
}

function validateBySelector(s) {
    var result = true;
    var l = $(s).each(function(index, item) {
        result &= validate(item);
    });
    return result;
}

function grayScreen(b) {
    var width = $('body').width();
    var height = $('#wrapper').height();
    if (b) {
        $('#lockScreen').bgiframe();
        $('#lockScreen').removeClass('lockOff', 0);
        $('#lockScreen').addClass('processTransaction', 0);
        $('#lockScreen').width(width);
        $('#lockScreen').height(height);
    }
    else {
        $('#lockScreen').width(width);
        $('#lockScreen').height(height);
        $('#lockScreen').removeClass('processTransaction', 0);
        $('#lockScreen').addClass('lockOff', 0);
    }
}

function lockScreenForProcess() {
    grayScreen(true);
}

/************************* VALIDATOR [END] ***********************************/
/*****************************************************************************/
/************************* UTILS [START] *************************************/

function clearTableSelection(table) {
    var rs = table.rows;
    for (var i = 1; i < rs.length; i++) {
        if (! rs[i].className.match('empty'))
            rs[i].className = 'nonSelectedRow';
    }
}

function getTableValue(table, row, col) {
    var colobj = table.rows[row].cells[col].childNodes;
    if (colobj.length==0) return "";
    return colobj[0].data;
}

/************************* UTILS [END] ***********************************/
/*****************************************************************************/
/************************* ADMIN [START] *************************************/

var unavailable_role = 'SBR';

function onRowClick(obj) {
    var table = document.getElementById('userTable');
    var roleid = table.rows[obj.rowIndex].cells[2].getAttribute('name');
    if (roleid == unavailable_role)
        return;
    clearTableSelection(table);
    clearUserForm();
    setUserForm(
        getTableValue(table, obj.rowIndex, 0),
        getTableValue(table, obj.rowIndex, 1),
        roleid);
    obj.className = 'selectedRow';
    var username = document.getElementById('username');
    username.readOnly = true;
    applyReadOnlyStyle(username, true);
    document.getElementById('deleteuser').disabled = false;
    document.getElementById('submituser').setAttribute('name', 'update');
}

function onClearUserForm() {
    clearTableSelection(document.getElementById('userTable'));
    clearUserForm();
}

function clearUserForm() {
    var form = document.getElementById('userForm');
    setUserForm('', '', 'USR');
    var username = document.getElementById('username');
    username.readOnly = false;
    applyReadOnlyStyle(username, false);
    document.getElementById('deleteuser').disabled = true;
    document.getElementById('submituser').setAttribute('name', 'create');
    cleanFormErrorMsg(form);
}

function setUserForm(username, fullname, role) {
    document.getElementById('username').value = username;
    document.getElementById('fullname').value = fullname;
    document.getElementById('role').value = role;
}

function upperCase(obj) {
    var u = obj.value.toUpperCase();
    if (u!=obj.value) {
        obj.value = obj.value.toUpperCase();
    }
}

/************************* ADMIN [END] ***************************************/
/*****************************************************************************/

$.extend($.ui.tabs.prototype, {
    abort2: function(XMLHttpRequest) {
        var self = this;
        self.element.dequeue("tabs");
        self._cleanup();
        var panelid = self.panels[self.options.selected].id;
        displayErrorMessage(panelid, XMLHttpRequest);
    },
    clearothers: function() {
        var self = this;
        var panelid = self.panels[self.options.selected].id;
        for (var pi = 0; pi<self.panels.length; pi++) {
            if (self.panels[pi].id!=panelid) {
                var id = self.panels[pi].id;
                $('#' + id).html("");
            }
        }
    }
});

function deleteMRow(obj) {
    $(obj).closest('tr').remove();
}

function cloneMRow(tplRowId, insBeforeId, ixFieldId) {
    var nextindex = document.getElementById(ixFieldId);
    var newid = parseInt(nextindex.value);
    nextindex.value = newid + 1;

    var erow = $('#' + tplRowId);
    var template = erow.clone();
    template.attr('id', tplRowId + newid);
    template.find('input').each(function(index, item) {
        var name = item.getAttribute('name');
        var id = item.getAttribute('id');
        if (name) {
            item.setAttribute('name', name + newid);
            if (id) {
                item.setAttribute('id', id + newid);
                var vr = document.getElementById(id).validation_rules;
                item.validation_rules = vr;
            }
        }
    });
    template.insertBefore($('#' + insBeforeId));
}

function appendChar(ch, field, dovalidate) {
    var f = document.getElementById(field);
    var tmp = f.value;

    //IE support
    if (document.selection) {
        f.focus();
        sel = document.selection.createRange();
        sel.text = ch;
    }
    //MOZILLA/NETSCAPE support
    else if (f.selectionStart || f.selectionStart == '0') {
        var startPos = f.selectionStart;
        var endPos = f.selectionEnd;
        f.value = f.value.substring(0, startPos)
        + ch
        + f.value.substring(endPos, f.value.length);
        f.selectionStart = startPos + ch.length;
        f.selectionEnd = startPos + ch.length;
    } else {
        f.value += ch;
    }

    if (dovalidate) {
        if (!validate(f) || f.maxLength < f.value.length) {
            f.value = tmp;
        }
    }
    validate(f)
    f.focus();
}
function replaceAmp(str) {
	return str.replace("&amp;", "&");
}
function uploadFile(button, url, filename, onSubmitCallback, onCompleteCallback) {
    jQuery(document).ready( function() {
        var oldval = button.val();
        var progressInterval;
        var failureInterval;
        var au = new AjaxUpload(button,{
            action: url,
            name: filename,
            onSubmit : function(file, ext){
                if (onSubmitCallback) {
                    onSubmitCallback(filename);
                }
                // change button text, when user selects file
                button.val('Uploading');
                
                // If you want to allow uploading only 1 file at time,
                // you can disable upload button
                this.disable();

                // Uploding -> Uploading. -> Uploading...
                progressInterval = window.setInterval(function(){
                    var text = button.val();
                    if (text.length < 13){
                        button.val(text + '.');
                    } else {
                        button.val('Uploading');
                    }
                }, 200);
                
                failureInterval = window.setInterval(function(){
                    if (onCompleteCallback) {
                        onCompleteCallback(false, filename, 'Timeout occured');
                    }
                    window.clearInterval(progressInterval);
                    window.clearInterval(failureInterval);
                    button.val(oldval);
                    au.enable();
                }, 30000);
            },
            onComplete: function(file, response){
                button.val(oldval);
                window.clearInterval(progressInterval);
                window.clearInterval(failureInterval);

                // enable upload button
                this.enable();

                // IE
                if (response.substring(0, 4)=='<pre') {
                	response = $(response).text(); // MOZILLA, CHROME
                }
                if ("reload"==response) {
                	window.location.reload(true);
                	return;
                }
                if (response.substring(0, 9) == "redirect:") {
                	window.location.href = response.substring(9);
                	return;
                }
                if (onCompleteCallback) {
                	onCompleteCallback(true, filename, response);
                }
            }
        });
    });
}
